<?php
/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Wall
 * @copyright  Copyright Hire-Experts LLC
 * @license    http://www.hire-experts.com
 * @version    $Id: Core.php 2011-04-26 11:18:13 michael $
 * @author     Michael
 */

/**
 * @category   Application_Extensions
 * @package    Wall
 * @copyright  Copyright Hire-Experts LLC
 * @license    http://www.hire-experts.com
 */

class Wall_Api_Core extends Activity_Api_Core {
	// overridden
	public function getPluginLoader() {
		if (null === $this->_pluginLoader) {
			$path = Engine_Api::_ ()->getModuleBootstrap ( 'wall' )->getModulePath ();
			$this->_pluginLoader = new Zend_Loader_PluginLoader ( array ('Wall_Model_Helper_' => $path . '/Model/Helper/' ) );
		}
		
		return $this->_pluginLoader;
	}
	
	public function assemble($body, array $params = array(), $action = null) {
		// Translate body
		$body = $this->getHelper ( 'translate' )->direct ( $body );
		
		// Do other stuff
		preg_match_all ( '~\{([^{}]+)\}~', $body, $matches, PREG_SET_ORDER );
		foreach ( $matches as $match ) {
			$tag = $match [0];
			$args = explode ( ':', $match [1] );
			$helper = array_shift ( $args );
			
			$helperArgs = array ();
			foreach ( $args as $arg ) {
				if (substr ( $arg, 0, 1 ) === '$') {
					$arg = substr ( $arg, 1 );
					$helperArgs [] = (isset ( $params [$arg] ) ? $params [$arg] : null);
				} else {
					$helperArgs [] = $arg;
				}
			}
			
			$helper = $this->getHelper ( $helper );
			if ($action) {
				$helper->setAction ( $action );
			}
			$r = new ReflectionMethod ( $helper, 'direct' );
			$content = $r->invokeArgs ( $helper, $helperArgs );
			$content = preg_replace ( '/\$(\d)/', '\\\\$\1', $content );
			$body = preg_replace ( "/" . preg_quote ( $tag ) . "/", $content, $body, 1 );
		}
		
		return $body;
	}
	
	protected $manifest_types = array ();
	protected $settings = array ();
	
	public function getManifestType($type) {
		if (isset ( $this->manifest_types [$type] )) {
			return $this->manifest_types [$type];
		}
		
		$modules = Engine_Api::_ ()->getDbTable ( 'modules', 'core' )->getEnabledModuleNames ();
		$data_array = array ();
		foreach ( Zend_Registry::get ( 'Engine_Manifest' ) as $data ) {
			if (empty ( $data [$type] )) {
				continue;
			}
			foreach ( $data [$type] as $key => $subdata ) {
				
				// is enabled module
				if (isset ( $subdata ['module'] ) && ! in_array ( $subdata ['module'], $modules )) {
					continue;
				}
				$data_array [$key] = $subdata;
			}
		}
		
		$this->manifest_types [$type] = $data_array;
		
		return $data_array;
	}
	
	public function setItemsType($items) {
		$types = array ();
		foreach ( $items as $item ) {
			
			$type = $item ['type'];
			$id = $item ['id'];
			
			if (! isset ( $types [$type] )) {
				$types [$type] = array ();
			}
			$types [$type] [] = $id;
		
		}
		return $types;
	}
	
	public function setItemsGuid($items) {
		$new_items = array ();
		foreach ( $items as $item ) {
			
			$guid = $item ['type'] . '_' . $item ['id'];
			
			if (! isset ( $new_items [$guid] )) {
				$new_items [$guid] = array ();
			}
			$new_items [$guid] = $item;
		
		}
		return $new_items;
	}
	
	public function guidsToItems($guids) {
		$items = array ();
		foreach ( $guids as $guid ) {
			$parts = explode ( '_', $guid );
			if (count ( $parts ) == 2) {
				$items [] = array ('type' => $parts [0], 'id' => $parts [1] );
			}
		}
		return $items;
	}
	
	public function getItems($items) {
		$item_array = array ();
		
		foreach ( $this->setItemsType ( $items ) as $type => $ids ) {
			
			if (! Engine_Api::_ ()->hasItemType ( $type )) {
				continue;
			}
			$table = Engine_Api::_ ()->getItemTable ( $type );
			
			$matches = $table->info ( 'primary' );
			$primary = array_shift ( $matches );
			if (! $primary) {
				continue;
			}
			
			foreach ( $this->getTableItems ( $table, $ids ) as $item ) {
				if (! isset ( $item_array [$type] )) {
					$item_array [$type] = array ();
				}
				$item_array [$type] [$item->{$primary}] = $item;
			}
		
		}
		
		$ready_items = array ();
		foreach ( $items as $item ) {
			
			$type = $item ['type'];
			$id = $item ['id'];
			
			if (! isset ( $item_array [$type] ) || ! isset ( $item_array [$type] [$id] )) {
				continue;
			}
			$ready_items [] = $item_array [$type] [$id];
		}
		
		return $ready_items;
	
	}
	
	public function getTableItems(Zend_Db_Table_Abstract $table, $ids) {
		try {
			$matches = $table->info ( 'primary' );
			$primary = array_shift ( $matches );
			if (! $primary) {
				return;
			}
			$select = $table->select ()->where ( "$primary IN (?)", $ids );
			
			return $table->fetchAll ( $select );
		
		} catch ( Exception $e ) {
			return;
		}
	}
	
	public function getHostUrl() {
		return (_ENGINE_SSL ? 'https://' : 'http://') . $_SERVER ['HTTP_HOST'];
	}
	
	public function getUrl($params, $route = null, $reset = null) {
		$host_url = Engine_Api::_ ()->wall ()->getHostUrl ();
		$url = Zend_Controller_Front::getInstance ()->getRouter ()->assemble ( $params, $route, $reset );
		
		return $host_url . $url;
	}
	
	public function getUrlContent($url, $postdata = null, $ssl = false) {
		$curl = curl_init ();
		curl_setopt ( $curl, CURLOPT_URL, $url );
		curl_setopt ( $curl, CURLOPT_FAILONERROR, 1 );
		curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );
		
		if ($ssl) {
			curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, FALSE );
			curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, 2 );
		}
		if ($postdata) {
			curl_setopt ( $curl, CURLOPT_POST, 1 );
			curl_setopt ( $curl, CURLOPT_POSTFIELDS, $postdata );
		}
		$content = curl_exec ( $curl );
		curl_close ( $curl );
		return $content;
	}
	
	public function getService($provider) {
		if (! $provider) {
			return;
		}
		$services = Engine_Api::_ ()->wall ()->getManifestType ( 'wall_service' );
		if (! array_key_exists ( $provider, $services )) {
			return;
		}
		return $services [$provider];
	}
	
	public function getServiceClass($provider) {
		$service = $this->getService ( $provider );
		if (! $service) {
			return;
		}
		return Engine_Api::_ ()->loadClass ( @$service ['plugin'] );
	}
	
	public function isPhotoType($type) {
		$album_types = array ('album_photo', 'event_photo', 'group_photo', 'profile_photo', 'pagealbumphoto' );
		
		if (in_array ( $type, $album_types )) {
			return true;
		}
		return false;
	}
	
	public function getMutualFriendsPaginator(User_Model_User $subject, User_Model_User $user) {
		$table = Engine_Api::_ ()->getDbTable ( 'users', 'user' );
		$membership = Engine_Api::_ ()->getDbTable ( 'membership', 'user' )->info ( 'name' );
		
		$select = $table->select ()->from ( array ('u' => $table->info ( 'name' ) ), new Zend_Db_Expr ( 'u.*' ) )->join ( array ('m' => $membership ), 'u.user_id = m.resource_id AND m.user_id = ' . $subject->getIdentity () . ' AND m.active = 1', array () )->join ( array ('vm' => $membership ), 'u.user_id = vm.resource_id AND vm.user_id = ' . $user->getIdentity () . ' AND vm.active = 1', array () )->where ( 'u.user_id <> ?', $user->getIdentity () )->group ( 'u.user_id' );
		
		return Zend_Paginator::factory ( $select );
	}
	
	public function getItemsLike($params = array()) {
		$subject = (isset ( $params ['subject'] )) ? Engine_Api::_ ()->getItemByGuid ( $params ['subject'] ) : null;
		
		if (! $subject) {
			return;
		}
		
		$table = Engine_Api::_ ()->getDbTable ( 'users', 'user' );
		$like_name = Engine_Api::_ ()->getDbTable ( 'likes', 'core' )->info ( 'name' );
		
		$select = $table->select ()->from ( array ('u' => $table->info ( 'name' ) ), new Zend_Db_Expr ( 'u.*' ) )->join ( array ('l' => $like_name ), 'u.user_id = l.poster_id AND poster_type = "user"', array () )->where ( 'l.resource_type = ?', $subject->getType () )->where ( 'l.resource_id = ?', $subject->getIdentity () )->group ( 'u.user_id' );
		
		if (! empty ( $params ['search'] )) {
			$select->where ( 'u.username LIKE ? OR u.displayname LIKE ?', '%' . $params ['search'] . '%' );
		}
		
		return Zend_Paginator::factory ( $select );
	
	}
	
	public function assembleUrl($params) {
		$route = 'default';
		if (! empty ( $params ['route'] )) {
			$route = $params ['route'];
			unset ( $params ['route'] );
		}
		$reset = true;
		if (! empty ( $params ['reset'] )) {
			$reset = $params ['reset'];
			unset ( $params ['reset'] );
		}
		
		return Zend_Controller_Front::getInstance ()->getRouter ()->assemble ( $params, $route, $reset );
	
	}
	
	var $_settings = array ();
	
	public function getUserSetting($viewer) {
		if (! $viewer) {
			return;
		}
		if (! ($viewer instanceof User_Model_User)) {
			return;
		}
		if (! isset ( $this->_settings [$viewer->getGuid ()] )) {
			$this->_settings [$viewer->getGuid ()] = Engine_Api::_ ()->getDbTable ( 'userSettings', 'wall' )->getUserSetting ( $viewer );
		}
		return $this->_settings [$viewer->getGuid ()];
	}
	
	public function getLikeTipTypes() {
		return array ('user', 'page', 'group', 'event' );
	}
	
	public function isOwnerTeamMember($subject, $user) {
		$page = $this->getSubjectPage ( $subject );
		if (! $page) {
			return;
		}
		return $page->isTeamMember ( $user );
	}
	
	protected $_items = array ();
	
	public function getSubjectPage($subject) {
		if (! $subject) {
			return;
		}
		if (! $this->isPageModule ( $subject->getType () )) {
			return;
		}
		if (! isset ( $subject->page_id ) && $subject->getType () != 'pagealbumphoto') {
			return;
		}
		$page_id = 0;
		
		if ($subject->getType () == 'page') {
			
			$page = $subject;
		
		} else {
			
			if ($subject->getType () == 'pagealbumphoto') { // :))
				

				$collection = $subject->getCollection ();
				if (! $collection) {
					return;
				}
				$page_id = $collection->page_id;
			
			} else {
				$page_id = $subject->page_id;
			}
			$guid = 'page_' . $page_id;
			if (! isset ( $this->_items [$guid] )) {
				$this->_pages [$guid] = Engine_Api::_ ()->getItem ( 'page', $page_id );
			}
			$page = $this->_pages [$guid];
		}
		if (! $page) {
			return;
		}
		return $page;
	}
	
	public function isPageModule($type) {
		if (substr ( $type, 0, 4 ) == 'page' || $type == 'playlist') {
			return true;
		}
		return false;
	}

}